package com.alibaba.yinan.word;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.util.List;

/**
 * 读取word中的数据
 *
 * @author yinan
 * @Date 2025/10/16 14:28
 */
@Service
public class WordToJsonExample {

    public JSONObject parseWordToJson(String filePath) throws Exception {
        JSONObject result = new JSONObject();
        JSONArray paragraphArray = new JSONArray();
        JSONArray tableArray = new JSONArray();

        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            // === 1. 读取段落 ===
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText().trim();
                if (!text.isEmpty()) {
                    paragraphArray.add(text);
                }
            }

            // === 2. 读取表格 ===
            for (XWPFTable table : document.getTables()) {
                JSONArray rowsArray = new JSONArray();
                List<XWPFTableRow> rows = table.getRows();
                if (rows.isEmpty()) continue;

                // 第一行为表头
                List<XWPFTableCell> headerCells = rows.get(0).getTableCells();
                int colCount = headerCells.size();
                String[] headers = new String[colCount];
                for (int i = 0; i < colCount; i++) {
                    headers[i] = headerCells.get(i).getText().trim();
                }

                // 读取每一行的数据
                for (int i = 1; i < rows.size(); i++) {
                    JSONObject rowObj = new JSONObject();
                    List<XWPFTableCell> cells = rows.get(i).getTableCells();
                    for (int j = 0; j < Math.min(colCount, cells.size()); j++) {
                        rowObj.put(headers[j], cells.get(j).getText().trim());
                    }
                    rowsArray.add(rowObj);
                }

                // 每个表格独立保存
                JSONObject tableObj = new JSONObject();
                tableObj.put("headers", headers);
                tableObj.put("rows", rowsArray);
                tableArray.add(tableObj);
            }

            // === 3. 汇总 JSON ===
            result.put("paragraphs", paragraphArray);
            result.put("tables", tableArray);
        }

        return result;
    }
}
